from socket import *
from multiprocessing import *
from dict_db import *#导入模块


# 自定义进程类做事情
class Handle(Process):
    def __init__(self, conn):
        self.conn = conn
        self.db=DictData()#创建数据库处理对象
        super().__init__()  # 为了得到父类的实例变量

    # 做事的地儿
    def run(self):
        #循环接受请求并响应
        while True:
            #接受请求
            request=self.conn.recv(128)
            print(request)
            #分情况讨论


class DICTServer:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self._create_socket()

    # 创建tcp套接字并绑定地址
    def _create_socket(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    # 启动服务函数 监听窗口
    def start_service(self):
        self.sock.listen(5)
        print("监听的窗口%d" % self.port)
        # 循环连接客户端，循环处理信息
        while True:
            # 等待接受链接
            conn, addr = self.sock.accept()
            print("链接来自于", addr)
            # 自定义进程类创建进程，用多进程来接受并处理请求
            p = Handle(conn)  # 一定要传连接套接字参数
            p.start()  # 启动进程并自动调用run方法函数


if __name__ == '__main__':
    dict = DICTServer(host="0.0.0.0", port=8888)
    dict.start_service()
